﻿using System;
using System.Collections.Generic;
using IWMAG.Core.EnhancedProperties.PropertyNodes;
namespace IWMAG.Core.EnhancedProperties.ResourceProperties
{
    public sealed class DynamicResource<T> : IResource<T>, IDisposable
    {
        internal DynamicResource(T value)
        {
            this._val = value;
            this.observers = new List<IResourceObserver<T>>();
        }

        private T _val;
        public T Value
        {
            get
            {
                return _val;
            }
            set
            {
                if (value is IComparable<T>)
                {
                    var newV = value as IComparable<T>;
                    if (newV.CompareTo(_val) == 0)
                    {
                        return;
                    }

                }

                _val = value;
                NotifyObserversResourceChanged(_val);

            }
        }

        private void NotifyObserversResourceChanged(T newVal)
        {
            foreach (var item in observers)
            {
                item.ResourceChanged(newVal);
            }
        }

        private List<IResourceObserver<T>> observers;

        void IResource<T>.AddObserver(IResourceObserver<T> newObserver)
        {
            observers.Add(newObserver);
        }

        void IResource<T>.RemoveObserver(IResourceObserver<T> oldObserver)
        {
            observers.Remove(oldObserver);
        }

        public void Dispose()
        {
            foreach (var item in observers)
            {
                item.ResourceDisposed();
            }

            observers.Clear();

            observers = null;
        }
    }

}
